package com.opbx.freeswitch.extension;


import com.opbx.freeswitch.CallCenterInit;
import com.opbx.freeswitch.entity.ExtensionUser;
import link.thingscloud.freeswitch.esl.InboundClient;
import link.thingscloud.freeswitch.esl.transport.message.EslMessage;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @Author: wwy
 * @Date: 2023/6/28 16:22
 */
@Component
public class ExtensionService {

    public static String FREE_SWITCH_BASE = "C:\\Program Files\\FreeSWITCH";

    /**
     * 获取已注册分机信息
     * @return
     */
    public Map<String,String> getRegistrations(){
        InboundClient inboundClient = InboundClient.getInstance();
        EslMessage eslMessage = inboundClient.sendSyncApiCommand(CallCenterInit.freesWitchAdd, "show", "registrations");
        List<String> bodyLines = eslMessage.getBodyLines();
        for (String bodyLine : bodyLines) {
            System.out.println(bodyLine);
        }
        return null;

    }

    /**
     * 获取所有用户
     * @return
     */
    public List<ExtensionUser> getUserListOnListUsers(){
        List<ExtensionUser> extensionUserList = new ArrayList<>();
        InboundClient inboundClient = InboundClient.getInstance();
        EslMessage eslMessage = inboundClient.sendSyncApiCommand(CallCenterInit.freesWitchAdd, "list_users", null);
        List<String> bodyLines = eslMessage.getBodyLines();
        //判断最后一行是否包含OK;
        if(bodyLines.get(bodyLines.size()).equalsIgnoreCase("+OK")){
            //获取成功
            //处理报文，遇见空字符串元素结束
            for (int i = 0; i < bodyLines.size(); i++) {
                String bodyLine = bodyLines.get(i);
                if(StringUtils.isEmpty(bodyLine)){
                    //结束
                    break;
                }else{
                    //判断是否为第一行，第一行，不进行解析
                    if(i == 0){
                        continue;
                    }
                    //用|拆分字符串为数组
                    String[] split = bodyLine.split("\\|");
                    ExtensionUser extensionUser = new ExtensionUser();
                    extensionUser.setUserid(split[0]);
                    extensionUser.setContext(split[1]);
                    extensionUser.setDomain(split[2]);
                    extensionUser.setGroup(split[3]);
                    extensionUser.setContact(split[4]);
                    extensionUser.setCallgroup(split[5]);
                    extensionUser.setEffective_caller_id_name(split[6]);
                    extensionUser.setEffective_caller_id_number(split[7]);
                    extensionUserList.add(extensionUser);
                }
            }

        }else{
            //获取失败
            return null;
        }
        return extensionUserList;

    }

    /**
     * 获取xml配置
     * @return
     */
    public List<ExtensionUser> getUserListOnUserXml(){
        List<ExtensionUser> extensionUserList = new ArrayList<>();
        //读取目录下所有配置文件
        File userDefaultFile = new File(FREE_SWITCH_BASE+"\\conf\\directory\\default");
        //分机文件列表
        File[]  extensionFileList= userDefaultFile.listFiles();
        for (File file : extensionFileList) {
            //判断fileName是否为纯数字
            String fileName = file.getName().replace(".xml","").replace(".XML","");
            boolean fileNameIsNumber = fileName.matches("\\d+");
            if(!fileNameIsNumber){
                continue;
            }


            //读取文件
            //创建解析器
            SAXReader saxReader = new SAXReader();
            //解析指定的XML文件
            try {
                Map<String,String> variableMap = new HashMap<>();
                Document document = saxReader.read(file);
                Element rootElement = document.getRootElement();
                String rootName = rootElement.getName();
                if(!"include".equals(rootName)){
                    continue;
                }
                //用户节点
                Element userElement = rootElement.element("user");
                String userId = userElement.attributeValue("id");
                variableMap.put("userid",userId);
                //params节点
                String password = "";
                Element paramsElement = userElement.element("params");
                Iterator<Element> paramElementIterator = paramsElement.elementIterator("param");
                while (paramElementIterator.hasNext()){
                    Element paramElement = paramElementIterator.next();
                    String name = paramElement.attributeValue("name");
                    if("password".equals(name)){
                        //密码
                        password = paramElement.attributeValue("value");
                        break;
                    }
                }
                variableMap.put("password",password);
                //variables节点

                Element variablesElement = userElement.element("variables");
                Iterator<Element> variableElementIterator = variablesElement.elementIterator("variable");
                while (variableElementIterator.hasNext()){
                    Element variableElement = variableElementIterator.next();
                    String name = variableElement.attributeValue("name");
                    String value = variableElement.attributeValue("value");
                    variableMap.put(name,value);
                }
                ExtensionUser extensionUser = new ExtensionUser();
                extensionUser.setUserid(variableMap.get("userid"));
                extensionUser.setPassword(variableMap.get("password"));
                extensionUser.setContext(variableMap.get("user_context"));
                extensionUser.setCallgroup(variableMap.get("callgroup"));
                extensionUser.setEffective_caller_id_name(variableMap.get("effective_caller_id_name"));
                extensionUser.setEffective_caller_id_number(variableMap.get("effective_caller_id_number"));
                extensionUserList.add(extensionUser);
            } catch (DocumentException e) {
                throw new RuntimeException(e);
            }
        }
        return extensionUserList;

    }

    /**
     * 添加用户
     * @return
     */
    public int addUserXml(String userId,String password){
        int status = 0;
        String xml = "<include>\n" +
                "  <user id=\""+ userId+"\">\n" +
                "    <params>\n" +
                "      <param name=\"password\" value=\""+password+"\"/>\n" +
                "      <param name=\"vm-password\" value=\"1003\"/>\n" +
                "    </params>\n" +
                "    <variables>\n" +
                "      <variable name=\"toll_allow\" value=\"domestic,international,local\"/>\n" +
                "      <variable name=\"accountcode\" value=\"1003\"/>\n" +
                "      <variable name=\"user_context\" value=\"default\"/>\n" +
                "      <variable name=\"effective_caller_id_name\" value=\"Extension 1003\"/>\n" +
                "      <variable name=\"effective_caller_id_number\" value=\"1003\"/>\n" +
                "      <variable name=\"outbound_caller_id_name\" value=\"$${outbound_caller_name}\"/>\n" +
                "      <variable name=\"outbound_caller_id_number\" value=\"$${outbound_caller_id}\"/>\n" +
                "      <variable name=\"callgroup\" value=\"techsupport\"/>\n" +
                "    </variables>\n" +
                "  </user>\n" +
                "</include>";
        String userFileName = userId+".xml";
        File userFile = new File(FREE_SWITCH_BASE+"\\conf\\directory\\default\\"+userFileName);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(userFile);
            fileOutputStream.write(xml.getBytes());
            fileOutputStream.flush();
            status = 1;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        EslMessage reloadxml = InboundClient.getInstance().sendSyncApiCommand("192.168.1.4:8021", "reloadxml", "");
        return status;
    }

}
